package cn.smart.epic.modular.system.controller;

import cn.smart.epic.common.controller.BaseController;
import cn.smart.epic.common.exception.InvalidKaptchaException;
import cn.smart.epic.core.log.LogManager;
import cn.smart.epic.core.log.factory.LogTaskFactory;
import cn.smart.epic.core.shiro.ShiroKit;
import cn.smart.epic.core.shiro.ShiroUser;
import cn.smart.epic.core.support.HttpKit;
import cn.smart.epic.core.util.ToolUtil;
import com.google.code.kaptcha.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Auther Z.B
 * @date 2017/10/13 15:19
 * @Email 2545375@qq.com
 * @Description 登陆控制器
 * @since 1.0
 */

@Controller
public class LoginController extends BaseController {


    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public ShiroUser loginVali(){
        String useName = super.getPara("username").trim();
        String password =super.getPara("password").trim();

        if (ToolUtil.getKaptchaOnOff()) {
            String kaptch = super.getPara("kaptcha").trim();
            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);

            if (StringUtils.isEmpty(kaptch) || !code.equals(kaptch)) {
                throw new InvalidKaptchaException();
            }
        }

        Subject currentUser= ShiroKit.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(useName,password.toCharArray());
        token.setRememberMe(true);

        currentUser.login(token);

        ShiroUser user = ShiroKit.getShiroUser();
        super.getSession().setAttribute("shiroUser",user);
        super.getSession().setAttribute("username",user.getAccount());

        LogManager.me().executeLog(LogTaskFactory.loginLog(user.getId(), HttpKit.getIp()));

        ShiroKit.getSession().setAttribute("sessionFlag",true);

        return user;
    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(){
        LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getShiroUser().getId(),HttpKit.getIp()));
        ShiroKit.getSubject().logout();
        return "1";
    }
}
